<?php

namespace apiend\modules\user\models;

use Yii;
use yii\db\Exception;
use yii\helpers\Json;
use common\models\user\UserGallery;
use common\helpers\ArrayHelper;

class AlbumForm extends \common\base\Model {

    /**
     * @name $user_id
     * @var integer 用户UID
     */
    public $user_id;

    /**
     * @var string 动态包含的图片集合，base64转义的json格式字符串
     */
    public $images;

    /**
     * @var string 格式化后的图片集合
     */
    private $pics = [];

    /**
     * @var string 格式化后的图片集合
     */
    private $_deletes = [];

    /**
     * {@inheritdoc}
     */
    public function rules() {
        return [
            [['user_id'], 'integer'],
            ['images', 'required'],
            [['images'], 'string'],
            ['images', 'formatImage'],
        ];
    }

    /**
     * 格式化图集内容
     */
    public function formatImage($attribute) {
        if ($this->hasErrors() || !$this->$attribute) {
            return;
        }
        $safeImages = base64_decode($this->$attribute);
        $pics = Json::decode($safeImages);
        $images = [];
        foreach ($pics as $key => $image) {
            $path = str_replace(Yii::getAlias('@attachUrl'), '', $image);
            $images[$key] = [
                'user_id' => $this->user_id,
                'image' => $path,
            ];
        }
        $this->pics = $images;
    }

    /**
     * 保存图集信息
     * @return mixed
     */
    public function save() {
        if (!$this->validate()) {
            return $this->dumpError('图库更新失败');
        }
        $data = [];
        if (!empty($this->pics)) {
            $albums = UserGallery::findAll(['user_id' => $this->user_id]);
            $aids = ArrayHelper::getColumn($albums, 'id');
            $transaction = Yii::$app->db->beginTransaction();
            try {
                foreach ($this->pics as $listorder => $pic) {
                    $model = UserGallery::findOrNew($pic);
                    $model->listorder = $listorder;
                    if (!$model->save()) {
                        throw new Exception('图片保存失败！');
                    }
                    ArrayHelper::removeValue($aids, $model->id);
                    $data[] = $model->toArray();
                }
                $transaction->commit();
            } catch (Exception $e) {
                $transaction->rollBack();
                return $this->dumpError($e->getMessage());
            }
            if (!empty($aids)) {
                UserGallery::deleteAll(['id' => $aids]);
            }
        } else {
            UserGallery::deleteAll(['user_id' => $this->user_id]);
        }
        return $data;
    }

}
